/**
 * Created by Administrator on 2018/4/16 0016.
 */
import config from '../../../../../config/config.js'

// components
import Icon from '../../../../basic/icon/index.vue'
import DateTable from '../../base/date-table.vue'
import YearTable from '../../base/year-table.vue'
import MonthTable from '../../base/month-table.vue'
import TimePicker from '../time/time-range.vue'
import Confirm from '../../base/confirm.vue'

import { toDate, initTimeDate, formatDateLabels } from '../../util'
import datePanelLabel from './date-panel-label.vue'

import Mixin from '../panel-mixin'
import DateMixin from './date-panel-mixin'
// mixins
import Locale from '../../../../../mixins/locale.js'

const prefixCls = config.prefix + '-picker-panel'
const datePrefixCls = config.prefix + '-date-picker'

const dateSorter = (a, b) => {
  if (!a || !b) return 0
  return a.getTime() - b.getTime()
}

export default {
  name: 'RangeDatePickerPanel',
  mixins: [Mixin, Locale, DateMixin],
  components: { Icon, DateTable, YearTable, MonthTable, TimePicker, Confirm, datePanelLabel },
  props: {
    // more props in the mixin
    splitPanels: {
      type: Boolean,
      default: false
    },
    rangetype: {
      type: String,
      default: 'date'
    }
  },
  data () {
    const [minDate, maxDate] = (Artery.isEmptyArray(this.value) ? [null, null] : this.value).map(date => date || initTimeDate())
    const leftPanelDate = this.startDate ? this.startDate : minDate
    const rightPanelDate = this.rangetype === 'monthrange' ?
      new Date(leftPanelDate.getFullYear() + 1, leftPanelDate.getMonth(), leftPanelDate.getDate()) :
      new Date(leftPanelDate.getFullYear(), leftPanelDate.getMonth() + 1, leftPanelDate.getDate())

    return {
      prefixCls: prefixCls,
      datePrefixCls: datePrefixCls,
      dates: this.value,
      rangeState: { from: this.value[0], to: this.value[1], selecting: minDate && !maxDate },
      currentView: this.selectionMode || 'range',
      leftPickerTable: `${this.selectionMode}-table`,
      rightPickerTable: `${this.selectionMode}-table`,
      leftPanelDate: leftPanelDate,
      rightPanelDate: rightPanelDate,
      onlyTimeRange: false
    }
  },
  computed: {
    classes () {
      return [
                `${prefixCls}-body-wrapper`,
                `${datePrefixCls}-with-range`,
                {
                  [`${prefixCls}-with-sidebar`]: this.shortcuts.length,
                  [`${datePrefixCls}-with-week-numbers`]: this.showWeekNumbers
                }
      ]
    },
    leftDatePanelLabel () {
      return this.panelLabelConfig('left')
    },
    rightDatePanelLabel () {
      return this.panelLabelConfig('right')
    },
    leftDatePanelView () {
      return this.leftPickerTable.split('-').shift()
    },
    rightDatePanelView () {
      return this.rightPickerTable.split('-').shift()
    },
    timeDisabled () {
      return !(this.dates[0] && this.dates[1])
    },
    preSelecting () {
      const tableType = `${this.currentView}-table`

      return {
        left: this.leftPickerTable !== tableType,
        right: this.rightPickerTable !== tableType
      }
    },
    panelPickerHandlers () {
      return {
        left: this.preSelecting.left ? this.handlePreSelection.bind(this, 'left') : this.handleRangePick,
        right: this.preSelecting.right ? this.handlePreSelection.bind(this, 'right') : this.handleRangePick
      }
    }
  },
  watch: {
    value (newVal) {
      const minDate = newVal[0] ? toDate(newVal[0]) : null
      const maxDate = newVal[1] ? toDate(newVal[1]) : null
      this.dates = [minDate, maxDate].sort(dateSorter)

      this.rangeState = {
        from: this.dates[0],
        to: this.dates[1],
        selecting: false
      }

      // set panels positioning
      this.resetPanel()
    },
    currentView (currentView) {
      const leftMonth = this.leftPanelDate.getMonth()
      const rightMonth = this.rightPanelDate.getMonth()
      const isSameYear = this.leftPanelDate.getFullYear() === this.rightPanelDate.getFullYear()

      if (currentView === 'date' && isSameYear && leftMonth === rightMonth) {
        this.changePanelDate('right', 'Month', 1)
      }
      if (currentView === 'month' && isSameYear) {
        this.changePanelDate('right', 'FullYear', 1)
      }
      if (currentView === 'year' && isSameYear) {
        this.changePanelDate('right', 'FullYear', 10)
      }
    },
    selectionMode (type) {
      this.currentView = type || 'range'
    }
  },
  methods: {
    reset () {
      this.currentView = this.selectionMode
      this.leftPickerTable = `${this.currentView}-table`
      this.rightPickerTable = `${this.currentView}-table`
    },
    resetPanel () {
      const leftPanelDate = this.startDate || this.dates[0] || new Date()
      this.leftPanelDate = leftPanelDate
      if (leftPanelDate) {
        const rightPanelDate = this.rangetype === 'monthrange' ?
          new Date(leftPanelDate.getFullYear() + 1, leftPanelDate.getMonth(), leftPanelDate.getDate()) :
          new Date(leftPanelDate.getFullYear(), leftPanelDate.getMonth() + 1, leftPanelDate.getDate())
        this.rightPanelDate = this.splitPanels ? new Date(Math.max(this.dates[1], rightPanelDate)) : rightPanelDate
      } else {
        this.rightPanelDate = new Date()
      }
    },
    panelLabelConfig (direction) {
      const locale = this.t('i.locale')
      const datePanelLabel = this.t('i.datepicker.datePanelLabel')
      const handler = type => {
        const fn = type == 'month' ? this.showMonthPicker : this.showYearPicker
        return () => fn(direction)
      }

      const date = this[`${direction}PanelDate`]
      const { labels, separator } = formatDateLabels(locale, datePanelLabel, date)

      return {
        separator: separator,
        labels: labels.map(obj => ((obj.handler = handler(obj.type)), obj))
      }
    },
    prevYear (panel) {
      const increment = this.currentView === 'year' ? -10 : -1
      this.changePanelDate(panel, 'FullYear', increment)
    },
    nextYear (panel) {
      const increment = this.currentView === 'year' ? 10 : 1
      this.changePanelDate(panel, 'FullYear', increment)
    },
    prevMonth (panel) {
      this.changePanelDate(panel, 'Month', -1)
    },
    nextMonth (panel) {
      this.changePanelDate(panel, 'Month', 1)
    },
    changePanelDate (panel, type, increment) {
      const current = new Date(this[`${panel}PanelDate`])
      current[`set${type}`](current[`get${type}`]() + increment)
      this[`${panel}PanelDate`] = current

      if (this.splitPanels) {
        // change other panel if dates overlap
        const otherPanel = panel === 'left' ? 'right' : 'left'
        if (panel === 'left' && this.leftPanelDate >= this.rightPanelDate) {
          this.changePanelDate(otherPanel, type, 1)
        }
        if (panel === 'right' && this.rightPanelDate <= this.leftPanelDate) {
          this.changePanelDate(otherPanel, type, -1)
        }
      } else {
        // keep the panels together
        const otherPanel = panel === 'left' ? 'right' : 'left'
        const otherCurrent = new Date(this[`${otherPanel}PanelDate`])
        otherCurrent[`set${type}`](otherCurrent[`get${type}`]() + increment)
        if (current[`get${type}`]() !== otherCurrent[`get${type}`]()) {
          this[`${otherPanel}PanelDate`] = otherCurrent
        }
      }
    },
    showYearPicker (panel) {
      this[`${panel}PickerTable`] = 'year-table'
    },
    showMonthPicker (panel) {
      this[`${panel}PickerTable`] = 'month-table'
    },
    handlePreSelection (panel, value) {
      this[`${panel}PanelDate`] = value
      const currentViewType = this[`${panel}PickerTable`]
      if (currentViewType === 'year-table') this[`${panel}PickerTable`] = 'month-table'
      else this[`${panel}PickerTable`] = `${this.currentView}-table`

      if (!this.splitPanels) {
        const otherPanel = panel === 'left' ? 'right' : 'left'
        const type = currentViewType === 'year-table' ? 'FullYear' : 'Month'
        this[`${otherPanel}PanelDate`] = value
        this.changePanelDate(otherPanel, type, 1)
      }
    },
    handleRangePick (val) {
      if (this.rangeState.selecting) {
        /**
         * #event
         *
         * @name    pick-date-end
         * @param   date 日期类型
         * @body
         * @description  选择结束时间触发, 仅适用于range选择
         */
        this.$parent.$parent.$emit('pick-date-end', val)
      } else {
        /**
         * #event
         *
         * @name    pick-date-start
         * @param   date 日期类型
         * @body
         * @description 选择开始时间触发, 仅适用于range选择
         */
        this.$parent.$parent.$emit('pick-date-start', val)
      }
      if (this.rangeState.selecting || this.currentView === 'time') {
        if (this.currentView === 'time') {
          this.dates = val
        } else {
          const [minDate, maxDate] = [this.rangeState.from, val].sort(dateSorter)
          this.dates = [minDate, maxDate]
          this.rangeState = {
            from: minDate,
            to: maxDate,
            selecting: false
          }
        }
        this.handleConfirm(false)
      } else {
        if (this.onlyTimeRange) {
          this.dates = [val, val]
          this.rangeState = {
            from: val,
            to: null,
            selecting: false
          }
          this.handleConfirm(false)
        }
        this.rangeState = {
          from: val,
          to: null,
          selecting: true
        }
      }
    },
    handleChangeRange (val) {
      this.rangeState.to = val
    }
  },
  mounted () {
    this.onlyTimeRange = this.rangetype === 'onlytimerange'
  }
}
